package com.devMode.ProxyMode;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK动态代理实现
 */
public class JDKDynamicProxy {
    public static void main(String[] args){
        //定义一个people作为被代（dai）理的实例
        IPeople ple=new People();
        //定义一个handler
        InvocationHandler handle=new MyHandle(ple);

        //获得类加载器
        ClassLoader cl=ple.getClass().getClassLoader();

        //动态产生一个代（dai）理，下边两种方法均可
//        IPeople p=(IPeople) Proxy.newProxyInstance(cl, new Class[]{IPeople.class}, handle);
        IPeople p=(IPeople) Proxy.newProxyInstance(cl, ple.getClass().getInterfaces(), handle);

        //执行被代（dai）理者的方法。
        p.func();

        p.fun();
    }
}

class MyHandle implements InvocationHandler{


    //被代（dai）理的实例
    Object obj=null;

    //我要代（dai）理谁
    public MyHandle(Object obj){
        this.obj=obj;

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Object result=method.invoke(this.obj, args);
        return result;
    }

}

interface IPeople{

    public void fun();

    public void func();
}

//实际被代（dai）理的类
class People implements IPeople{

    @Override
    public void fun() {
        System.out.println("这是fun方法");

    }

    @Override
    public void func() {
        System.out.println("这是func方法");

    }

}
